package controllers;

import models.User;

import org.apache.commons.lang.StringUtils;

import play.Play;
import play.cache.Cache;
import play.mvc.Before;
import play.mvc.Controller;

public class AuthorityFilter extends Controller{

    
    public static void login() {
        render("/login.html");
    }
    
    @Before(unless = {"login", "authenticate","logout"})
    public static void filter() {
        if (!session.contains("userid")) {
            login();
        }
        String userid = session.get("userid");
        User user = User.findCurrentUser(userid);
        if (user == null) {
            login();
        }
        renderArgs.put("currentUser", user);
        
    }
    
    
    public static void authenticate(String username, String password){
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            login();
        }
        String adminUsername = Play.configuration.getProperty(User.ADMIN_USERNAME);
        String adminPassword = Play.configuration.getProperty(User.ADMIN_PASSWORD);
        if (StringUtils.equals(adminUsername, username) && StringUtils.equals(adminPassword, password)) {
            User admin = User.createAdmin();
            session.put("userid", admin.id);
            loginAdmin();
        }
        User user = User.auth(username, password);
        if (user != null) {
            User.findUser(user.id);
            session.put("userid", user.id);
            redirect("/");
        }
        login();
    }
    
    public static void loginAdmin() {
        render("/admin.html");
    }

    public static void logout() {
        session.clear();
        login();
    }
}
